//
//  FireworksHelper.swift
//  Game
//
//  Created by woniu on 2025/9/25.
//绽放烟花

import Foundation
import UIKit
import QuartzCore
import AVFoundation

class FireworksHelper: NSObject {
    static let shared = FireworksHelper()
    
    private var audioPlayer: AVAudioPlayer?
    
    /// 显示火箭和烟花效果
    /// - Parameters:
    ///   - view: 在哪个视图上显示效果
    ///   - position: 烟花爆炸的位置，默认为屏幕中心
    func showRocketAndFireworks(in view: UIView,showSuccess:Bool) {
        let explosionPoint = view.center
        
        //创建成功图案
        var successView:UIImageView?
        if showSuccess{
            successView = UIImageView(image: UIImage(named: "成功_勾"))
            successView?.contentMode = .scaleAspectFit
            successView?.frame = CGRectMake((view.centerX-75), view.centerY-200, 150, 150)
            successView?.alpha = 0
            view.addSubview(successView!)
            UIView.animate(withDuration: 1.5, delay: 0, options: .curveEaseOut, animations: {
                successView?.alpha = 1
            })
        }
        
        // 创建火箭图像视图
        let rocketImageView = UIImageView(image: UIImage(named: "火箭"))
        rocketImageView.contentMode = .scaleAspectFit
        // 设置火箭初始位置在视图底部之外
        rocketImageView.frame = CGRect(
            x: view.bounds.midX - 25,
            y: view.bounds.maxY,
            width: 50,
            height: 50
        )
        
        view.addSubview(rocketImageView)
        
        // 添加音效（如果可用）
        playFireworkSound()
        
        // 火箭从底部滑动到中心的动画
        UIView.animate(withDuration: 1.5, delay: 0, options: .curveEaseOut, animations: {
            rocketImageView.frame = CGRect(
                x: view.bounds.midX - 25,
                y: explosionPoint.y - 25,
                width: 50,
                height: 50
            )
        }) { _ in
            // 动画完成后移除火箭并显示烟花
            rocketImageView.removeFromSuperview()
            successView?.removeFromSuperview()
            self.showFireworks(at: explosionPoint, in: view)
        }
    }
    
    /// 显示烟花效果
    /// - Parameters:
    ///   - position: 烟花爆炸的位置
    ///   - view: 在哪个视图上显示烟花
    private func showFireworks(at position: CGPoint, in view: UIView) {
        // 创建爆炸效果
        let explosion = createExplosionEmitter()
        explosion.emitterPosition = position
        explosion.frame = view.bounds
        view.layer.addSublayer(explosion)
        
        // 立即爆炸
        explosion.birthRate = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            explosion.birthRate = 0
        }
        
        // 过一段时间后移除爆炸效果
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            explosion.removeFromSuperlayer()
        }
    }
    
    /// 创建爆炸效果
    private func createExplosionEmitter() -> CAEmitterLayer {
        let emitter = CAEmitterLayer()
        emitter.emitterShape = .point
        emitter.emitterMode = .outline
        emitter.renderMode = .unordered
        emitter.masksToBounds = false
        
        let colors: [UIColor] = [.red, .green, .blue, .yellow, .orange, .purple, .cyan, .magenta]
        var cells: [CAEmitterCell] = []
        
        for color in colors {
            let cell = CAEmitterCell()
            cell.birthRate = 80
            cell.lifetime = 3.0
            cell.lifetimeRange = 1.0
            cell.velocity = 150
            cell.velocityRange = 50
            cell.emissionRange = .pi * 2
            cell.spin = 0
            cell.spinRange = 4
            cell.scale = 0.15
            cell.scaleRange = 0.1
            cell.scaleSpeed = -0.03
            cell.color = color.cgColor
            cell.alphaSpeed = -0.2
            cell.contents = createParticleImage().cgImage
            
            cells.append(cell)
        }
        
        emitter.emitterCells = cells
        return emitter
    }
    
    /// 创建粒子图像
    private func createParticleImage() -> UIImage {
        let size = CGSize(width: 20, height: 20)
        let rect = CGRect(origin: .zero, size: size)
        
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        defer { UIGraphicsEndImageContext() }
        
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
        
        // 创建一个明亮的星星形状粒子
        context.setFillColor(UIColor.white.cgColor)
        context.fillEllipse(in: rect.insetBy(dx: 2, dy: 2))
        
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
    
    /// 播放烟花音效
    private func playFireworkSound() {
        // 在实际项目中，你可以在这里添加真实的音效文件
        // 示例代码：
        /*
         guard let soundURL = Bundle.main.url(forResource: "firework", withExtension: "mp3") else { return }
         do {
         audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
         audioPlayer?.play()
         } catch {
         print("无法播放音效: \(error)")
         }
         */
    }
}
